package com.zj.study.controller;

import com.zj.study.pojo.FinalResultVO;
import com.zj.study.pojo.entity.User;
import com.zj.study.repository.UserRepository;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author ZhaoJiu
 * @desc 使用 WebFlux 整合 mongodb
 * @since 2021/7/21
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserApiController {


  private final UserRepository userRepository;

  public UserApiController(UserRepository userRepository) {
    this.userRepository = userRepository;
  }

  /**
   * 根据用户名称查询
   *
   * @param username 用户名称
   * @return 用户数据
   */
  @GetMapping("findByName/{username}")
  public Mono<FinalResultVO<User>> findByName(@PathVariable("username") String username) {
    return userRepository.findUserByUsername(username)
        .flatMap(i -> Mono.just(FinalResultVO.ok(i)));
  }

  /**
   * 修改用户
   *
   * @param user 用户数据
   * @return 成功返回200 失败返回404
   */
  @PutMapping("update")
  public Mono<FinalResultVO<User>> update(@RequestBody User user) {
    return userRepository.findById(user.getId())
        .flatMap(u -> userRepository.save(user))
        .map(FinalResultVO::ok)
        .defaultIfEmpty(FinalResultVO.fail(new User(), "用户未找到"));
  }

  /**
   * 删除用户
   *
   * @param id 用户id
   * @return 成功返回200 失败返回404
   */
  @DeleteMapping("delete/{id}")
  public Mono<FinalResultVO<Void>> delete(@PathVariable String id) {
    return userRepository.findById(id)
        .flatMap(
            user -> userRepository.delete(user)
                .then(Mono.just(FinalResultVO.ok("操作成功"))))
        .defaultIfEmpty(FinalResultVO.fail("操作失败,用户不存在"));
  }

  /**
   * 添加用户
   *
   * @param user 用户数据
   * @return mono
   */
  @PostMapping("save")
  public Mono<User> save(@RequestBody User user) {
    return userRepository.save(user);
  }

  /**
   * 查询所有用户
   *
   * @return Flux<User>
   */
  @GetMapping("list")
  public Mono<FinalResultVO<List<User>>> list() {
    return userRepository.findAll()
        .collectList()
        .flatMap(i -> Mono.fromSupplier(() -> FinalResultVO.ok(i)));
  }

  /**
   * 通过响应式流返回数据
   *
   * @return 数据
   */
  @GetMapping(value = "stream/list", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
  public Flux<User> getAll() {
    return userRepository.findAll();
  }

}
